package com.wangxiaonan.wxwork.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.domain.Agent;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.service.AgentService;
import com.wangxiaonan.wxwork.service.TokenService;
import com.wangxiaonan.wxwork.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author: wangxiaonan
 * @Date: 2018/8/23
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private AgentService agentService;
    @Resource
    private TokenService tokenService;

    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String simpleList(@RequestParam(value = "agent_id") String agentId,
                             @RequestParam(value = "department_id") String deptId,
                             @RequestParam(value = "fetch_child", required = false) String fetchChild) {
        JSONObject rs = new JSONObject();
        rs.put("status", "ok");
        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            rs.put("status", "agent_not_exists");
            return rs.toJSONString();
        }
        String token;
        try {
            token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
        } catch (ServiceException e) {
            rs.put("status", e.getCode());
            rs.put("msg", e.getMsg());
            return rs.toJSONString();
        }

        JSONObject jsonObject = userService.getUserList(token, deptId, fetchChild);
        if ("0".equals(jsonObject.getString("errcode"))) {
            JSONArray userList = jsonObject.getJSONArray("userlist");
            rs.put("data", userList);
        } else {
            rs.put("status", "user_list_fail");
        }

        return rs.toJSONString();
    }

}
